import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;

import lexer.Lexer;
import lexer.Preprocessor;
import parser.Parser;
import parser.Quaternion;

public class Compiler extends JFrame {
    // 定义组件
    JPanel jp1 = new JPanel(new GridLayout(1, 2, 10, 0));
    JPanel jp2 = new JPanel(new GridLayout(2, 1));
    // 代码输入
    JPanel code = new JPanel(new BorderLayout());
    JLabel codeTextAreLabel = new JLabel("请输入代码:");
    JTextArea codeTextArea = new JTextArea();
    // 编译结果
    JPanel result = new JPanel(new BorderLayout());
    JLabel resultTextAreaLabel = new JLabel("编译结果:");
    JTextArea resultTextArea = new JTextArea("请点击编译");
    JLabel outputLabel = new JLabel("……");//
    JButton runButton = new JButton("编译");// 编译按钮

    public static void main(String[] args) {
        new Compiler();
    }

    public Compiler() {
        runButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Preprocessor pre = new Preprocessor("");
                    Lexer lexer = new Lexer("");
                    Parser parser = new Parser();
                    pre.readCode(codeTextArea.getText());
                    pre.preprocess();
                    lexer.readCode(pre.getCode());
                    parser.setTokens(lexer.scan());
                    parser.run();
                    ArrayList<Quaternion> qList = new ArrayList<>(parser.getQList());
                    StringBuilder sb = new StringBuilder();
                    for (Quaternion q : qList) {
                        sb.append(q + "\n");
                    }
                    outputLabel.setText("编译成功!");
                    resultTextArea.setText(sb.toString());
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (Error e2) {
                    outputLabel.setText(e2.getMessage());
                }
            }
        });
        // 添加组件
        code.add(codeTextAreLabel, BorderLayout.NORTH);
        code.add(codeTextArea, BorderLayout.CENTER);
        result.add(resultTextAreaLabel, BorderLayout.NORTH);
        result.add(resultTextArea, BorderLayout.CENTER);
        jp1.add(code);
        jp1.add(result);
        jp2.add(outputLabel);
        jp2.add(runButton);
        this.add(jp1, BorderLayout.CENTER);
        this.add(jp2, BorderLayout.SOUTH);
        // 设置窗体
        this.setSize(960, 540);
        this.setTitle("Little C 编译器");
        setLocationRelativeTo(null);
        // 显示
        this.setVisible(true);
        // 退出窗体后将JFrame同时关闭
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}